var currentpage = 1, totalpage = 1, pagesize = 10;//当前页、总页数
$(function () {
	callfetsetcoursefun("#onrecruit");
	getsetcarousel();
	//日期格式化
	formatDate();
});
//日期格式化
function formatDate() {
	Date.prototype.format = function (format) {
		var o = {
			"M+": this.getMonth() + 1, //month
			"d+": this.getDate(),    //day
			"H+": this.getHours(),   //hour
			"m+": this.getMinutes(), //minute
			"s+": this.getSeconds(), //second
			"q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
			"S": this.getMilliseconds() //millisecond
		}
		if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
			(this.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (var k in o) if (new RegExp("(" + k + ")").test(format))
			format = format.replace(RegExp.$1,
				RegExp.$1.length == 1 ? o[k] :
					("00" + o[k]).substr(("" + o[k]).length));
		return format;
	}
}
//切换标签时查询课程
$('#recruitmainpage a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
	//防太过频繁切换标签，发送过多请求
	if (previouspage.nowtime && $(e.target.hash).find("a").length && (Date.now() - previouspage.nowtime < 5000)) {
		adjustHeight();
		return;
	}
	previouspage.nowtime = Date.now();
	$('#container>img[alt="loading"]').fadeIn(100);
	currentpage = 1;
	var divid = e.target.getAttribute("href");
	callfetsetcoursefun(divid);
});
//调用获取设置课程方法
function callfetsetcoursefun(divid) {
	var queryLessones = function (type) {
		var sucessfct = function (data) {
			currentpage = data.currentPageNo;
			totalpage = data.totalPageCount;
			pagesize = data.pagesize;
			fillcontent(data.result, divid);
		};
		$.ajax({
			url: "publishlessons/queryresult",
			type: "POST",
			contentType: "application/json",
			data: JSON.stringify({
				owner: UserID,
				pageindex: currentpage,
				pagesize: pagesize,
				modeid: type
			}),
			dataType: "json",
			success: sucessfct,
			error: function (event) {
				window.parent.parentLayermsg(langThis("role_optionfaild"));
				$('#container>img[alt="loading"]').fadeOut();
				// console.log(event);
			}
		});
	};
	switch (divid) {
		case "#onrecruit": queryLessones(2); break;//正招生
		case "#pauserecruit": queryLessones(3); break;//已暂停
		case "#stoprecruit": queryLessones(4); break;//已停止
	}
}
//调整父页面高度
function adjustHeight() {
	$('#container>img[alt="loading"]').fadeOut();
	setTimeout(function () {
		// 子页面设置父页面iframe高度
		if (window.parent.setiframeHeight) {
			var ht = $("#container").height();
			ht = ht > 800 ? ht : 800;
			window.parent.setiframeHeight(ht);
		}
	}, 100);
}
//填充课程
function fillcontent(data, divid) {
	if (!data.length) {
		$(divid).html('<div class="askcreatcourse"><p><a target="_blank" href="./cOmCourse" ><span class="glyphicon glyphicon-plus" aria-hidden="true"></span>' + langThis("kc_creat_course") + '</a></p></div>');
		$("#partpagenavbar").fadeOut();
		$('#container>img[alt="loading"]').fadeOut();
		adjustHeight();
		return;
	}
	var courses = "";
	for (var i in data) {
		courses += '<div class="row lsrow"><div class="col-xs-3 lsimgdiv">';
		courses += '<a target="_blank" href="./recruit?lid=' + data[i].id + '&p=' + data[i].phase + '">';
		courses += '<img class="lessoncoverimg" src="' + data[i].image + '" title="' + langThis("rt_recruitlist") + '" alt="LessonAvatar"></a></div>';
		courses += '<div class="col-xs-6 lscontent">';
		var tagString = '<span class="badge lessonenddate">' + langThis("rm_csEndTime") + ' : ' + new Date(data[i].enddate).format("yyyy-MM-dd") + '</span><br>';
		tagString += ' <span class="badge lessonTypeTag">' + (/zh/.test(getCurrentLang()) ? data[i].typenamecn : data[i].typenameen) + '</span> ';
		tagString += data[i].phase && data[i].phase != 1 ? ' <span class="badge lessonSstag"> ' + langThis("cm_coursePhase").replace("{p}", data[i].phase) + '</span>' : "";
		courses += '<h4>' + data[i].name + '</h4>' + tagString + '</div>';
		courses += '<div class="col-xs-3 actionbtn"><div class="btn-group">';
		// 按钮
		//课程详情
		courses += '<a href="./lessonDetail?lid=' + data[i].id + '&p=' + data[i].phase + '" target="_blank" title="' + langThis("ms_lessDetail") + '" type="button" class="btn btn-primary"><span class="glyphicon glyphicon-th-list"></span></a>';
		//招生管理
		courses += '<a href="./recruit?lid=' + data[i].id + '&p=' + data[i].phase + '" target="_blank" title="' + langThis("rt_recruitlist") + '" type="button" class="btn btn-info"><span class="glyphicon glyphicon-book"></span></a>';
		switch (divid) {
			case "#onrecruit": {
				// 暂停
				courses += '<button title="' + langThis("rm_pauserecruit") + '" type="button" class="btn btn-warning" onclick="pauseRecruit(' + data[i].id + ',' + data[i].phase + ',\'' + divid + '\')"><span class="glyphicon glyphicon-pause"></span></button>';
				// 停止
				courses += '<button title="' + langThis("rm_stoprecruit") + '" type="button" class="btn btn-danger" onclick="stopRecruit(' + data[i].id + ',' + data[i].phase + ',\'' + divid + '\')"><span class="glyphicon glyphicon-off"></span></button>';
			} break;//正招生
			case "#pauserecruit": {
				// 继续
				courses += '<button title="' + langThis("rm_continuerecruit") + '" type="button" class="btn btn-warning" onclick="continueRecruit(' + data[i].id + ',' + data[i].phase + ',\'' + divid + '\')"><span class="glyphicon glyphicon-play"></span></button>';
				// 停止
				courses += '<button title="' + langThis("rm_stoprecruit") + '" type="button" class="btn btn-danger" onclick="stopRecruit(' + data[i].id + ',' + data[i].phase + ',\'' + divid + '\')"><span class="glyphicon glyphicon-off"></span></button>';
			} break;//已暂停
		}
		courses += '</div></div></div>';
	}

	$(divid).html(courses);
	setpartpagebar(divid);
	adjustHeight();
}
//轮播
function getsetcarousel() {
	$.ajax({
		url: "publishlessons/studentstatistics",
		type: "POST",
		contentType: "application/json",
		data: JSON.stringify({ "owner": UserID }),
		dataType: "json",
		success: function (data) {
			if (data.rows && data.rows.length) {
				fillcarousel(data.rows);
			} else {
				$('#recruitstatic,h4[data-localize="rm_recruitstatic"]').hide();
			}
		},
		error: function (event) {
			window.parent.parentLayermsg(langThis("role_optionfaild"));
			$('#container>img[alt="loading"]').fadeOut();
			// console.log(event);
		}
	});
}
function fillcarousel(data) {
	var carousel = $("#recruitstatic");
	if (!data.length) {
		carousel.hide();
		return;
	}
	var tpg = Math.ceil(data.length / 6);//轮播页数
	// 填充
	var indicators = "";
	var items = "";
	for (var i = 0; i < tpg; i++) {
		if (i == 0) {
			indicators += tpg > 1 ? '<li data-target="#recruitstatic" data-slide-to="' + i + '" class="active"></li>' : "";
			items += '<div class="item row active">';
		} else {
			indicators += '<li data-target="#recruitstatic" data-slide-to="' + i + '"></li>';
			items += '<div class="item row">';
		}
		var j = i * 6;
		while (j < (i + 1) * 6) {
			if (!data[j]) { break; }
			items += '<div class="col-xs-2">';
			items += '<a href="./recruit?lid=' + data[j].id + '&p=' + data[j].phase + '" target="_blank">';
			items += '<img src="' + data[j].image + '" title="' + data[j].lessonname + '" alt="courseAvatar"></a>';
			items += data[j].phase && data[j].phase != 1 ? '<span class="badge psFlag">' + langThis("cm_coursePhase").replace("{p}", data[j].phase) + '</span>' : "";
			items += '<div class="row">';
			items += '<div class="col-xs-6"><h4>' + data[j].totalstudentnb + '</h4>' + langThis("rm_accRecruit") + '</div>';
			items += '<div class="col-xs-6"><h4>' + data[j].currentnb + '</h4>' + langThis("rm_crtRecruit") + '</div>';
			items += '</div></div>';
			j++;
		}
		items += '</div>';
	}
	items += '</div>';
	carousel.find("ol.carousel-indicators").html(indicators);
	carousel.find("div.carousel-inner").html(items);
	//课程封面比例控制
	$("#recruitstatic div.item>div img").height($("#recruitstatic div.item>div img").width() / 1.8);
}
// 修改课程状态
function changecoursemode(lsid, ps, divid,modeid){
	return function(){
		$.ajax({
			url: "publishlessons/" + lsid + "/" + ps + "/changemode",
			type: "POST",
			contentType: "application/json",
			data: JSON.stringify({
				"modeid": modeid
			}),
			dataType: "json",
			success: function (data) {
				window.parent.parentCloseAll();
				callfetsetcoursefun(divid);
			},
			error: function (event) {
				window.parent.parentCloseAll();
				window.parent.parentLayermsg(langThis("role_optionfaild"));
				// console.log(event);
			}
		});
	 };
}
//停止招生
function stopRecruit(lsid, ps, divid) {
	var title = {};
	title.text = "<span class='glyphicon glyphicon-exclamation-sign'></span>&nbsp;" + langThis("rm_stoprecruit");
	title.css = {
		'color': "#fff",
		'background-color': '#d9534f',
		'font-weight': 'bold'
	};
	var masg = langThis("rm_stoprecruit_tip");
	var btn1 = langThis("kc_confirm");
	var btn2 = langThis("pm_cancle");
	var fun1 = changecoursemode(lsid, ps, divid,4);
	window.parent.parentLayerConfirm(title, masg, btn1, btn2, fun1);
}
//继续招生
function continueRecruit(lsid, ps, divid) {
	var title = {};
	title.text = "<span class='glyphicon glyphicon-info-sign'></span>&nbsp;" + langThis("rm_continuerecruit");
	title.css = {
		'color': "#fff",
		'background-color': '#5cb85c',
		'font-weight': 'bold'
	};
	var masg = langThis("rm_continuerecruit_tip");
	var btn1 = langThis("kc_confirm");
	var btn2 = langThis("pm_cancle");
	var fun1 = changecoursemode(lsid, ps, divid,2);
	window.parent.parentLayerConfirm(title, masg, btn1, btn2, fun1);
}
//暂停招生
function pauseRecruit(lsid, ps, divid) {
	var title = {};
	title.text = "<span class='glyphicon glyphicon-question-sign'></span>&nbsp;" + langThis("rm_pauserecruit");
	title.css = {
		'color': "#fff",
		'background-color': '#f0ad4e',
		'font-weight': 'bold'
	};
	var masg = langThis("rm_pauserecruit_tip");
	var btn1 = langThis("kc_confirm");
	var btn2 = langThis("pm_cancle");
	var fun1 = changecoursemode(lsid, ps, divid,3);
	window.parent.parentLayerConfirm(title, masg, btn1, btn2, fun1);
}
//分页控制
function setpartpagebar(divid) {
	var pagesli = '';
	//首页、上一页
	if (currentpage == 1 || totalpage == 1) {
		pagesli += '<li title="' + langThis("nav_master") + '" class="active"><a>&laquo;</a></li>';
		pagesli += '<li title="' + langThis("nav_pre") + '" class="active"><a>&lt;</a></li>';
	} else {
		pagesli += '<li title="' + langThis("nav_master") + '"><a style="cursor:pointer;" onclick="gotofirstpage(\'' + divid + '\')">&laquo;</a></li>';
		pagesli += '<li title="' + langThis("nav_pre") + '"><a style="cursor:pointer;" onclick="previouspage(\'' + divid + '\')">&lt;</a></li>';
	}
	//页码
	var startpage;
	if (currentpage - 5 <= 0) {
		startpage = 1;
	} else if (currentpage + 5 > totalpage) {
		startpage = totalpage - 9;
	} else {
		startpage = currentpage - 4;
	}
	// 左过长
	if (startpage > 1) {
		pagesli += '<li><a style="cursor:pointer;" onclick="gotopage(\'' + divid + '\',' + (startpage - 1) + ')">...</a></li>';
	} else {
		startpage = 1;
	}
	for (var j = startpage; j <= totalpage; j++) {
		if (j == currentpage) {
			pagesli += '<li class="active"><a>' + j + '</a></li>';
		} else {
			pagesli += '<li><a style="cursor:pointer;" onclick="gotopage(\'' + divid + '\',' + j + ')">' + j + '</a></li>';
		}
		//右过长
		if ((j == startpage + 9) && (j < totalpage)) {
			pagesli += '<li><a style="cursor:pointer;" onclick="gotopage(\'' + divid + '\',' + (startpage + 10) + ')">...</a></li>';
			break;
		}
	}
	//下一页、尾页
	if (currentpage == totalpage || totalpage == 1) {
		pagesli += '<li title="' + langThis("nav_next") + '" class="active"><a>&gt;</a></li>';
		pagesli += '<li title="' + langThis("nav_last") + '" class="active"><a>&raquo;</a></li>';
	} else {
		pagesli += '<li title="' + langThis("nav_next") + '"><a style="cursor:pointer;" onclick="nextpage(\'' + divid + '\')">&gt;</a></li>';
		pagesli += '<li title="' + langThis("nav_last") + '"><a style="cursor:pointer;" onclick="gotolastpage(\'' + divid + '\')">&raquo;</a></li>';
	}
	$("#partpagenavbar>ul.pagination").html(pagesli);
	$("#partpagenavbar").fadeIn();
}
function previouspage(divid) {
	currentpage--;
	callfetsetcoursefun(divid);
}
function nextpage(divid) {
	currentpage++;
	callfetsetcoursefun(divid);
}
function gotopage(divid, pagenum) {
	currentpage = pagenum;
	callfetsetcoursefun(divid);
}
function gotofirstpage(divid) {
	currentpage = 1;
	callfetsetcoursefun(divid);
}
function gotolastpage(divid) {
	currentpage = totalpage;
	callfetsetcoursefun(divid);
}
// 翻页快捷键
document.onkeydown = function (e) {
	var divid = $("#recruitmainpage>ul[role='tablist']>li.active>a").attr("href");
	if ((e || event).keyCode == 37 && currentpage > 1) {//上一页
		previouspage(divid);
	} else if ((e || event).keyCode == 39 && currentpage < totalpage) {//下一页
		nextpage(divid);
	} else if ((e || event).keyCode == 36 && currentpage != 1) {//首页
		gotofirstpage(divid);
	} else if ((e || event).keyCode == 35 && currentpage != totalpage) {//尾页
		gotolastpage(divid);
	}
};